﻿using System;
using System.Configuration;
using System.Web.Hosting;
using Lucene.Net.Store;
using Medianamik.Core.Configuration;
using System;

namespace Medianamik.Core.Index
{
	internal static class IndexUtils
	{
		
        private static readonly string _relativeDirectory = ((MedianamikConfigSection)ConfigurationManager.GetSection(ConfigurationSectionName.MEDIANAMIK)).IndexPath;
        private static Directory _indexDirectory;

	    public static Lucene.Net.Util.Version EngineVersion = Lucene.Net.Util.Version.LUCENE_29;
        private readonly static SimpleFSLockFactory LockFactory = new SimpleFSLockFactory();
        /// <summary>
        /// Crée une clé unique à partir du NodeId et du CultureName et du DocumentType
        /// </summary>
        /// <param name="pNodeId"></param>
        /// <param name="pCultureName"></param>
        /// <returns></returns>
        public static string GetDocumentKey(Guid pNodeId, string pCultureName)
        {
            var hashcode = pNodeId.GetHashCode()
                ^ (pCultureName ?? string.Empty).ToLowerInvariant().GetHashCode();
            return hashcode.ToString();
        }

	    public static string IndexDirectoryPath
	    {
            get { return HostingEnvironment.MapPath(_relativeDirectory) ?? ""; }
	    }

        public static Directory IndexDirectory
        {
            get
            {
                if (_indexDirectory == null)
                {
                    var dirInfo = new System.IO.DirectoryInfo(IndexDirectoryPath);
                    _indexDirectory =  FSDirectory.Open(dirInfo, LockFactory);
                }
                return _indexDirectory;
            }
        }
	}
}
